package com.tenement.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tenement.entity.Notice;
import com.tenement.mapper.NoticeMapper;
import com.tenement.service.NoticeService;
import com.tenement.vo.QueryVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.io.Serializable;

import static com.tenement.entity.table.NoticeTableDef.NOTICE;
import static com.tenement.entity.table.UserTableDef.USER;

/**
 *  服务层实现。
 *
 * @author BertXie
 * @since 1.0.1
 */
@Service
@RequiredArgsConstructor
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {

    private final NoticeMapper noticeMapper;

    @Override
    public Page<Notice> list(QueryVo queryVo) {
        QueryWrapper wrapper = QueryWrapper.create()
                .from(NOTICE)
                .select(
                        NOTICE.TITLE, NOTICE.CONTENT, NOTICE.PUBLISH_DATE, NOTICE.STATUS,
                        NOTICE.PUSH_ID,NOTICE.CREATE_TIME,NOTICE.TYPE,
                        NOTICE.ID, USER.REAL_NAME,USER.PHONE_NUMBER
                ).leftJoin(USER).on(NOTICE.PUSH_ID.eq(USER.ID))
                .where(
                        NOTICE.TITLE.like(queryVo.getKeyWord(), StrUtil.isNotEmpty(queryVo.getKeyWord()))
                                .or(USER.REAL_NAME.like(queryVo.getKeyWord(), StrUtil.isNotEmpty(queryVo.getKeyWord())))
                                .or(NOTICE.CONTENT.like(queryVo.getKeyWord(), StrUtil.isNotEmpty(queryVo.getKeyWord())))
                )
                .and(NOTICE.STATUS.eq(queryVo.getStatus(), queryVo.getStatus() != -1))
                .between("publish_date",queryVo.getTimeRange() == null ? "" : queryVo.getTimeRange().get(0), queryVo.getTimeRange() == null ? "" :  queryVo.getTimeRange().get(1),
                        CollectionUtil.isNotEmpty(queryVo.getTimeRange()) && queryVo.getTimeRange().size() == 2)
                .orderBy(NOTICE.PUBLISH_DATE.desc());
        return noticeMapper.paginate(queryVo.getPage(), queryVo.getSize(), wrapper);
    }

    @Override
    public boolean changeStatus(Serializable id, Short status) {
        return UpdateChain.of(Notice.class).set(NOTICE.STATUS, status).where(NOTICE.ID.eq(id)).update();
    }
}
